/*
 * Util.java
 *
 * Created on 14 de Maio de 2007, 06:30
 *
 */

package net.sf.jOpinionPoll.miscellaneous;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.GrantedAuthority;

/**
 * 
 * @author erico
 */
public class JOPUtil {
	/** Creates a new instance of Util */
	public JOPUtil() {
	}

	public String getContextName() {
		return FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
	}

	public String getActionAttribute(ActionEvent event, String name) {
		return (String) event.getComponent().getAttributes().get(name);
	}
	
	public static boolean hasRole(String role) {
		return hasRole(new String[] {role});
	}
	
	public static boolean hasRole(String[] roles) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        GrantedAuthority[] grantedAuthority = authentication.getAuthorities();
		
		for (GrantedAuthority ga : grantedAuthority) {
            for(String role : roles) {
                if (ga.getAuthority().equals(role)) {
                    return true;
                }
            }
        }
		
		return false;
	}

	public synchronized static String getMD5Hash(String string) {
		try {
			String hash;
			MessageDigest md5;

			md5 = MessageDigest.getInstance("MD5");
			md5.update(string.getBytes("UTF-8"));
			hash = new BigInteger(md5.digest()).abs().toString(16);

			return hash;
		} catch (NoSuchAlgorithmException e) {
			// Unusual exception. "MD5" is just hardcoded and supported.
			throw new RuntimeException(e);
		} catch (UnsupportedEncodingException e) {
			// Unusual exception. "UTF-8" is just hardcoded and supported.
			throw new RuntimeException(e);
		}
	}
	
	public static Map<String, String> requestParamMap() {
		return getFacesContext().getExternalContext().getRequestParameterMap();
	}
	
	public static String requestParam(String param) {
		return requestParamMap().get(param);
	}
    
    public static FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }
    
    public static ServletContext getServletContext() {
        return (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
    }
}